package services;

import dao.ProductInfo_Repository;
import models.DatabaseExecutionContext;
import models.Item_F_Entity;
import models.ProductInfo_T_Entity;
import play.db.jpa.JPAApi;

import javax.inject.Inject;
import javax.persistence.Query;
import java.util.List;
import java.util.concurrent.CompletionStage;

import static java.util.concurrent.CompletableFuture.supplyAsync;


/**
 * Provide JPA operations running inside of a thread pool sized to the connection pool
 */
public class ProductInfo_Repository_JPA implements ProductInfo_Repository {

    private final JPAApi jpaApi;
    private final DatabaseExecutionContext executionContext;

    @Inject
    public ProductInfo_Repository_JPA(JPAApi jpaApi, DatabaseExecutionContext executionContext) {
        this.jpaApi = jpaApi;
        this.executionContext = executionContext;
    }

    @Override
    public CompletionStage<ProductInfo_T_Entity> getProductByID (Integer ProductID)
    {
    	return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
            	Query query = entityManager.createQuery("select d from ProductInfo_T_Entity d where d.fdRowId = :ProductID ", ProductInfo_T_Entity.class).setParameter("ProductID", ProductID);
            	ProductInfo_T_Entity _tProductInfoEntity = new ProductInfo_T_Entity();
                if(query.getResultList().size() > 0)	
                {
                	_tProductInfoEntity = (ProductInfo_T_Entity)query.getResultList().get(0);
                }
                else
                {
                	// 单位不存在等“异常”情况，仍然以结构返回。但返回为0
                	_tProductInfoEntity.setFdRowId(0);
                }
                
                return _tProductInfoEntity;
            });
        }, executionContext);    	
    }
    
    @Override
    public CompletionStage<List<ProductInfo_T_Entity>> getProductList ()
    {
    	return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
            	return entityManager.createQuery("select d from ProductInfo_T_Entity d ", ProductInfo_T_Entity.class).getResultList();
            });
        }, executionContext);    	
    }

    public CompletionStage<List<Item_F_Entity>> getItemByType(String ItemType) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
                String strSql = "select * from f_GetItemByType('"+ ItemType +"')";
                return entityManager.createNativeQuery(strSql, Item_F_Entity.class).getResultList();
            });
        }, executionContext);
    }
}